package net.homelinux.chaoswg.io.renga.krypto.animations.Merge2;

import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;

import net.homelinux.chaoswg.io.renga.core.registries.GlobalPropertyRegistry;
import net.homelinux.chaoswg.io.renga.krypto.datatypes.numerical.UnsignedNBit;
import net.homelinux.chaoswg.io.renga.krypto.operations.type.Merge2;

public class Merge2StateChanger implements Runnable {
    JLabel firstOperandsDisplay;
    JLabel secondOperandsDisplay;
    JLabel resultDisplay;
    JFrame jw;
    
    Merge2 merge2 = new Merge2();
    
    final Merge2State initialState;
    
    public Merge2StateChanger (Merge2State initialState)  {
        this.initialState = initialState;

        jw = new JFrame ("Merge-2");
        jw.getContentPane().add(getPanel());
        jw.setLocationRelativeTo(null);
        
        jw.setSize(500, 100);
        
        
    }
    
    private JPanel getPanel() {
        JPanel toReturn = new JPanel (new GridLayout (2,1));
        JPanel north = new JPanel (new GridLayout (1,2));
        north.add (firstOperandsDisplay = new JLabel (initialState.getOperand0().toString()));
        north.add (secondOperandsDisplay = new JLabel (initialState.getOperand1().toString()));
        
        toReturn.add (north);
        toReturn.add (resultDisplay = new JLabel (initialState.getResult().toString()));
        
        

        firstOperandsDisplay.setHorizontalAlignment(JLabel.CENTER);
        secondOperandsDisplay.setHorizontalAlignment(JLabel.CENTER);
        resultDisplay.setHorizontalAlignment(JLabel.CENTER);

        toReturn.setBorder(new BevelBorder (BevelBorder.RAISED));

        return toReturn;
    }

    private void setNew () {
        firstOperandsDisplay.setText (initialState.getOperand0().toString());
        firstOperandsDisplay.paintImmediately(firstOperandsDisplay.getVisibleRect());
        secondOperandsDisplay.setText (initialState.getOperand1().toString());
        secondOperandsDisplay.paintImmediately(secondOperandsDisplay.getVisibleRect());
        resultDisplay.setText (initialState.getResult().toString());
        resultDisplay.paintImmediately(resultDisplay.getVisibleRect());
    }

    public void run() {
        int delay = ((Integer)GlobalPropertyRegistry.getGlobalPropertyRegistry().getProperty("animationSpeed")) * 100;

        jw.setVisible(true);

        setNew ();
        UnsignedNBit operand0= initialState.getOperand0();
        UnsignedNBit operand1 = initialState.getOperand1();
        try {
            Thread.sleep(delay);
        } catch (InterruptedException ie) {System.err.println ("ERR");}

        initialState.setResult(merge2.apply(operand0, operand1));
        setNew ();

        try {
            Thread.sleep(delay);
        } catch (InterruptedException ie) {}
    }

    public void close () {
        jw.dispose ();
    }
    
}
